package com.scy.jdbc.utils;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

//工具类
public class JDBCUtil {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
//    properties文件只读一次因此放在静态代码块中
static {
    try {
        //读取资源文件读取值
        //创建properties
        Properties pro = new Properties();
        //加载资源文件
        ClassLoader loader = JDBCUtil.class.getClassLoader();
        //动态获取src路径下的文件方式-类加载器
//        URL resource = loader.getResource("jdbc.properties");
//        //拿到path路径
//        String path = resource.getPath();
//        pro.load(new FileReader(path));
        InputStream is
                = loader.getResourceAsStream("jdbc.properties");
        pro.load(is);
        //获取文件的属性质
        url = pro.getProperty("url");
        user = pro.getProperty("user");
        password = pro.getProperty("password");
        driver = pro.getProperty("driver");
        //System.out.println(driver);
        //注册驱动
        Class.forName(driver);
    }  catch (IOException e) {
        throw new RuntimeException("资源文件找不到。。。");
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("数据库驱动类找不到。。。");
    }
}
//    获取链接
    public static Connection getConn(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(
                    url,user,password);
        } catch (SQLException e) {
            throw new RuntimeException("连接失败。。。");
        }
        return conn;
    }
//    释放资源
    //使用反射实现不同流对象的关闭
    //使用泛型，传递什么关什么
    public static <T> void closeIO(T t){
        //利用反射，获取class对象
        try {
            Class<?> aClass = t.getClass();
            Method close = aClass.getMethod("close");
            //执行方法
            close.invoke(t);
        } catch (Exception e) {
            throw new RuntimeException("关闭失败");
        }
    }


}
